import React, {Component, Fragment} from 'react';
import TodoItem from './TodoItem'

class TodoList extends Component {

    // 构造函数
    constructor(props) {
        super(props);
        // 组件的状态
        this.state = {
            inputValue: '',
            list: []
        };
        this.handleItemClick = this.handleItemClick.bind(this);
        this.handleButtonClick = this.handleButtonClick.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    render() {
        return (
            <Fragment>
                <div>
                    <input value={this.state.inputValue} onChange={this.handleInputChange}/>
                    <button onClick={this.handleButtonClick}>提交</button>
                </div>
                <ul>
                    {this.getTodoItem()}
                </ul>
            </Fragment>
        );
    }

    getTodoItem() {
        return this.state.list.map((item, index) => {
            return (<TodoItem key={index} content={item} index={index} deleteItem={this.handleItemClick}/>);
        })
    }

    handleInputChange(e) {
        const value = e.target.value
        this.setState(() => (
            {
                inputValue: value
            }))
    }

    handleButtonClick() {
        this.setState((prevState) => ({
            list: [...prevState.list, prevState.inputValue],
            inputValue: ''
        }))
    }

    handleItemClick(index) {
        this.setState((prevState) => {
            const list = [...prevState.list];
            list.splice(index, 1);
            return {list}
        });
    }

}

export default TodoList;